﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using SalesSys.BLL;
using SalesSys.Comm.BLL;
using SalesSys.Comm.Utility;
using SalesSys.DAL.Models;
using SalesSys.Site.Models;
using SalesSys.WebCore;
using SalesSys.WebCore.Authorize;
using System.Transactions;

namespace SalesSys.Site.Controllers.Api
{
    /// <summary>
    /// 锁价单
    /// </summary>
    [RoutePrefix("api/LockOrder")]
    public class LockOrderController : BaseApiController
    {
        private LockOrderBLL bll = BllFactory.GetBll<LockOrderBLL>();
        private EmployeeBLL employeeBLL = BllFactory.GetBll<EmployeeBLL>();
        private CustomerBLL customerBLL = BllFactory.GetBll<CustomerBLL>();
        private SupplierBLL supplierBLL = BllFactory.GetBll<SupplierBLL>();
        private AccountBLL accountBLL = BllFactory.GetBll<AccountBLL>();
        private DistrictBLL districtBLL = BllFactory.GetBll<DistrictBLL>();
        private ProviderBLL providerBll = BllFactory.GetBll<ProviderBLL>();
        private DepotCommodityRecordBLL depotCommodityRecordBLL = BllFactory.GetBll<DepotCommodityRecordBLL>();
        private CustomerBalanceBLL customerBalanceBll = new CustomerBalanceBLL();
        /// <summary>
        /// 锁价单列表
        /// </summary>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <param name="state">状态</param>
        /// <param name="keyword">模糊查询</param>
        [Route("List")]
        public ViewDto<IEnumerable<LockOrder>> Get(int page, int rows, OrderState? state = null, string keyword = null)
        {
            KeyValuePair<int, IEnumerable<LockOrder>> re;
            re = bll.Select(Guid.Empty, keyword, state, new QueryInfo { Page = page, Rows = rows });
            var dto = new ViewDto<IEnumerable<LockOrder>>();
            dto.Data = re.Value;
            dto.Total = re.Key;
            dto.Page = page;
            dto.Rows = rows;
            return dto;
        }

        /// <summary>
        /// 锁价单详情
        /// </summary>
        /// <param name="id">锁价单编号</param>
        [Route("Detail")]
        public LockOrder Get(Guid id)
        {
            var result = bll.Details(id);
            return result;
        }

        /// <summary>
        /// 创建锁价单
        /// </summary>
        /// <param name="model">锁价单实体类</param>
        [Route("Add")]
        [ApiUserRoleAuth(RolesConst.ClientManager, RolesConst.Admin)]
        public IResultState Add(LockOrderDto model)
        {
            try
            {
                using (var tran = new TransactionScope())
                {
                    PaymentInfoBLL paymentInfoBLL = new PaymentInfoBLL();
                    var order = model.ToEntity();
                    order.Creater = employeeBLL.Details(ClientHelper.ClientInfo.Id);
                    order.Customer = customerBLL.Details(model.CustomerId);
                    if (paymentInfoBLL.CheckExecuting(model.AccountId, order.Customer.Id,order.Creater.Id, PaymentStatus.Refund))
                        throw new ArgumentException("该账户正在退款审批中，不允许创建锁价单。");

                   
                    order.Account = accountBLL.Details(model.AccountId);
                    //if (order.Creater.Id != order.Customer.ClientManager.Id)
                    //{
                    //    return ReState.ArgError.Create("请选择您已报备的客户");
                    //}
                    //其他信息
                    order.CreateTime = DateTime.Now;
                    order.OrderType = OrderType.Normal;
                    order.State = OrderState.Pending;
                    order.Provider = providerBll.Details(model.ProviderId);
                    //判断是否是商品锁价
                    if (order.IsGoodsLock)
                    {
                        order.OrderType = OrderType.ProductLock;
                        order.DepotCommodityRecords = new List<DepotCommodityRecord>();
                        //查询仓库商品，然后转为历史价格记录
                        var dcmmdBll = new DepotCommodityBLL();
                        var comodityRecordId = Guid.Parse(model.depotCommodityRecordId.ToString());
                        var tmpInfo = dcmmdBll.GetDepotCommodity(model.ProviderId, comodityRecordId);
                        var newRecord = DepotCommodityRecord.ToDepotCommodityRecord(tmpInfo);

                        order.DepotCommodityRecords.Add(newRecord);//depotCommodityRecordBLL.Details(model.depotCommodityRecordId)
                    }
                    else
                    {
                        order.OrderType = OrderType.BasePriceLock;
                        //查询所有锁价商品列表
                        order.DepotCommodityRecords = depotCommodityRecordBLL.ReacordByNowDepotInfo(model.ProviderId);
                    }
                    order.IsStandard = !order.Account.IsCash;
                    //订单历史记录
                    order.Records = new List<OrderRecord>();
                    order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价单创建" });
                    order.ProcessState = ProcessState.LockPrice;
                    order.IsApproval = true;
                    order.IsPause = false;
                    order.CalcUnitDiscount();
                    if (order.Provider.Manager != null)
                        order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "等待[" + order.Provider.Manager.Name + "]锁价审批" });
                    bll.Create(order);

                    //提交锁价审批流程  
                    SequenceApprovalBLL.LockPriceOrderApproval approvalBll = new SequenceApprovalBLL.LockPriceOrderApproval();
                    approvalBll.Submit(order);


                    //先行判断该客户在余额表中是否存在
                    if (!customerBalanceBll.IsExistAccount(model.CustomerId, ClientHelper.ClientInfo.Id))
                    {
                        //判断该客户下有多少个户头
                        Customer customer = customerBLL.Details(model.CustomerId);
                        if (customer != null)
                        {
                            foreach (var item in customer.Accounts)
                            {
                                //添加账户余额
                                CustomerBalance customerBalance = new CustomerBalance();
                                customerBalance.EmployeeId = ClientHelper.ClientInfo.Id;
                                customerBalance.CustomerId = model.CustomerId;
                                customerBalance.AccountId = item.Id;
                                customerBalance.Id = Guid.NewGuid();
                                customerBalance.Balance = 0;
                                customerBalanceBll.Create(customerBalance);
                             
                            }
                        }
                    }
                    //SequenceApprovalBLL.LockPriceOrderApproval.ApprovalEndHandle += LockPriceOrderApproval_ApprovalEndHandle;
                    tran.Complete();
                    return ReState.Success.Create("保存成功");
                }
            }
            catch (Exception ex)
            {
                return ReState.ArgError.Create(ex.Message);
            }
        }

        /// <summary>
        /// 暂停/继续锁价单
        /// </summary>
        /// <param name="id">锁价单编号</param>
        [Route("IsPause")]
        [ApiUserRoleAuth(RolesConst.ClientManager, RolesConst.Admin)]
        public IResultState IsPause(Guid id)
        {
            var emp = employeeBLL.Details(ClientHelper.ClientInfo.Id);
            var order = bll.Details(id);
            order.IsPause = !order.IsPause;
            order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = emp.Name + "成功" + (order.IsPause ? "暂停" : "继续") + "锁价单" });
            bll.Edit(order);
            if (order.IsPause)
                return ReState.Success.Create("成功暂停锁价单");
            else
                return ReState.Success.Create("成功继续锁价单");
        }

        /// <summary>
        /// 支付锁价单
        /// </summary>
        /// <param name="id">锁价单编号</param>
        [Route("PayLockOrder")]
        [ApiUserRoleAuth(RolesConst.ClientManager, RolesConst.Admin)]
        public IResultState PayLockOrder(Guid id)
        {
            var emp = employeeBLL.Details(ClientHelper.ClientInfo.Id);
            var order = bll.Details(id);
            if (!(order.State == OrderState.Pending && order.IsPause))
            {
                return ReState.ArgError.Create("订单暂停后才可继续支付");
            }
            else
            {
                FinanceBLL financeBll = new FinanceBLL();
                var paymentSuccess = financeBll.PayLockOrder(order); //扣款
                //扣款是否成功
                if (paymentSuccess)
                {
                    order.IsPause = false;
                    order.State = OrderState.Checked;
                    order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价[扣款]成功" });
                }
                else
                {
                    order.IsPause = true;
                    order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "锁价[扣款]失败，余额不足。" });
                }
                bll.Edit(order);
            }
            return ReState.Success.Create("锁价单支付");
        }

        /// <summary>
        /// 取消锁价单
        /// </summary>
        /// <param name="id">锁价单编号</param>
        [Route("Cancel")]
        [ApiUserRoleAuth(RolesConst.ClientManager, RolesConst.Admin)]
        public IResultState Cancel(Guid id)
        {
            var emp = employeeBLL.Details(ClientHelper.ClientInfo.Id);
            var order = bll.Details(id);
            if (order.State == OrderState.Pending)
            {
                bll.Cancel(emp, id);
                return ReState.Success.Create("取消锁价单成功");
            }
            else
            {
                order.IsApproval = true;
                order.Records.Add(new OrderRecord { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, LinkId = emp.Id.ToString(), Remarks = "[" + emp.Name + "] 提交锁价单取消操作" });
                if (order.Provider.Manager != null)
                    order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "等待[" + order.Provider.Manager.Name + "]锁价单取消审批" });
                bll.Edit(order);

                //取消审批
                SequenceApprovalBLL.LockOrderRefundApproval cancelOrderBll = new SequenceApprovalBLL.LockOrderRefundApproval();
                cancelOrderBll.Submit(order, order.Total);//取消审批
                return ReState.Success.Create("进入取消锁价单审批流程");
            }
        }

        ///<summary>
        ///创建计划单
        ///</summary>
        ///<param name="id">锁价单编号</param>
        [Route("AddOrder")]
        [ApiUserRoleAuth(RolesConst.ClientManager, RolesConst.Admin)]
        public object AddOrder(Guid id)
        {
            var order = new Order();
            try
            {
                var lockOrder = bll.Details(id);
                order.Creater = employeeBLL.Details(ClientHelper.ClientInfo.Id);
                order.Customer = customerBLL.Details(lockOrder.Customer.Id);
                order.Account = accountBLL.Details(lockOrder.Account.Id);
                order.IsFullPayment = true;
                order.IsStandard = order.IsStandard;
                order.OrderType = lockOrder.OrderType;
                //其他信息
                order.Provider = lockOrder.Provider;
                order.Provider.Id = lockOrder.Provider.Id;
                order.Provider.Name = lockOrder.Provider.Name;
                order.OrderType = lockOrder.OrderType;
                order.ApplyDiscount = lockOrder.ApplyDiscount;
               
                //仓库历史记录转仓库商品编号
                var infoList = new List<DepotCommodity>();
                //查找实时库存
                var dcmmdBll = new DepotCommodityBLL();
                foreach (var item in lockOrder.DepotCommodityRecords)
                {
                    var depotCommodity = new DepotCommodity();
                    depotCommodity.CommodityId = item.Commodity.Id;
                    depotCommodity.Commodity = item.Commodity;
                    var dm = dcmmdBll.GetDepotCommodity(item.Provider.Id, item.Commodity.Id);
                    depotCommodity.Amount = dm != null ? dm.Amount : 0;
                    depotCommodity.Price = item.Price;
                    depotCommodity.Provider = item.Provider;
                    infoList.Add(depotCommodity);
                }
                //订单历史记录
                order.Records = new List<OrderRecord>();
                return new { Order = order, DepotCommodity = infoList, Surplus = lockOrder.GetSurplus() };
            }
            catch (Exception ex)
            {
                return order;
            }
        }


        /// <summary>
        /// 退款锁价单
        /// </summary>
        /// <param name="id">锁价单编号</param>
        [Route("Refund")]
        [ApiUserRoleAuth(RolesConst.ClientManager, RolesConst.Admin)]
        public IResultState Refund(Guid id)
        {
            var emp = employeeBLL.Details(ClientHelper.ClientInfo.Id);
            var order = bll.Details(id);
            if (order.State == OrderState.Pending)
            {
                return ReState.Error.Create("未确认订单不允许退款");
            }
            else if (order.IsApproval)
            {
                return ReState.Error.Create("审批中订单不允许退款");
            }
            else
            {
                decimal money = 0.0M;
                money =
                    order.Orders.Where(
                        p =>
                            p.State != OrderState.Cancel && p.State != OrderState.Refund && p.State != OrderState.Return)
                        .Sum(p => p.Total);
                //foreach (var item in order.Orders)
                //{
                //    money += item.Total;
                //}
                money = order.Total - money;
                if (order.State == OrderState.Refund)
                {
                    if (money <= order.Refund)
                        return ReState.Error.Create("该计划单已退款");
                    else
                        money = money - order.Refund;
                }
                if (money <= 0)
                    return ReState.Error.Create("该计划单无余款可退");
                order.IsApproval = true;
                //order.State = OrderState.Pending;
                order.Records.Add(new OrderRecord { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, LinkId = emp.Id.ToString(), Remarks = "[" + emp.Name + "] 提交锁价单退款操作" });
                if (order.Provider.Manager != null)
                    order.Records.Add(new OrderRecord() { CreateTime = DateTime.Now, DiscountType = DiscountType.Msg, Remarks = "等待[" + order.Provider.Manager.Name + "]锁价单退款审批" });
                bll.Edit(order);
                //退款审批
                SequenceApprovalBLL.LockOrderRefundApproval refundOrderBll = new SequenceApprovalBLL.LockOrderRefundApproval();
                refundOrderBll.Submit(order, money);//退款审批
                return ReState.Success.Create("进入退款锁价单审批流程");
            }
        }
    }
}